<template>
  <div class="current-borrow-container">
    <el-card>
      <template #header>
        <span>当前借阅</span>
      </template>

      <el-table :data="records" v-loading="loading" stripe>
        <el-table-column prop="title" label="书名" width="180" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="isbn" label="ISBN" width="130" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column 
          v-if="authStore.isAdmin" 
          prop="username" 
          label="借阅人" 
          width="120" 
        />
        <el-table-column prop="borrowDate" label="借阅日期" width="160">
          <template #default="{ row }">
            {{ formatDate(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'borrowed'" type="success">已借阅</el-tag>
            <el-tag v-else-if="row.status === 'pending_return'" type="warning">待确认归还</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!authStore.isAdmin"
              type="primary"
              size="small"
              @click="handleReturn(row)"
              :disabled="row.status === 'pending_return'"
            >
              归还
            </el-button>
            <el-button
              v-if="authStore.isAdmin && row.status === 'pending_return'"
              type="success"
              size="small"
              @click="handleConfirmReturn(row)"
            >
              确认归还
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import { borrowAPI } from '../services/api'

const authStore = useAuthStore()
const records = ref([])
const loading = ref(false)

const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await borrowAPI.getCurrentBorrows()
    records.value = response.records || []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const handleReturn = async (record) => {
  try {
    await ElMessageBox.confirm(`确定要归还《${record.title}》吗？`, '确认归还', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await borrowAPI.returnBook(record.id)
    ElMessage.success('归还申请已提交，等待管理员确认')
    await fetchRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '归还失败')
    }
  }
}

const handleConfirmReturn = async (record) => {
  try {
    await ElMessageBox.confirm(`确认《${record.title}》已归还？确认后该记录将移至借阅记录中。`, '确认归还', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await borrowAPI.confirmReturn(record.id)
    ElMessage.success('确认归还成功，该记录已移至借阅记录')
    await fetchRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '确认失败')
    }
  }
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.current-borrow-container {
  height: 100%;
}
</style>

